package com.d3works.apps.base.db.repo;

import com.d3works.apps.base.db.BankDetails;
import com.d3works.apps.base.db.Company;
import com.d3works.apps.base.exceptions.BaseExceptionMessage;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.i18n.I18n;
import javax.persistence.PostUpdate;

public class BankDetailsListener {
  @PostUpdate
  private void onPostUpdate(BankDetails bankDetails) throws D3worksException {
    if (bankDetails.getActive()) {
      Company company = bankDetails.getCompany();

      if (company != null) {
        for (BankDetails details : company.getBankDetailsList()) {
          if (!details.getId().equals(bankDetails.getId())
              && details.getIban().equals(bankDetails.getIban())
              && details.getActive()) {
            throw new D3worksException(
                TraceBackRepository.CATEGORY_INCONSISTENCY,
                I18n.get(BaseExceptionMessage.DUPLICATE_ACTIVE_BANK_DETAILS));
          }
        }
      }
    }
  }
}
